import { Injectable } from '@nestjs/common';
import { InjectRedis } from '@nestjs-modules/ioredis';
import Redis from 'ioredis';

@Injectable()
export class RedisCacheService {
  private readonly defaultTTL = 3600; // 默认 TTL：1 小时

  constructor(@InjectRedis() private readonly redis: Redis) {}

  async set(key: string, value: string, ttl?: number): Promise<void> {
    await this.redis.set(key, value, 'EX', ttl ?? this.defaultTTL);
  }

  async get(key: string): Promise<string | null> {
    return this.redis.get(key);
  }

  async setObject<T>(key: string, value: T, ttl?: number): Promise<void> {
    const serialized = JSON.stringify(value);
    await this.set(key, serialized, ttl);
  }

  async getObject<T>(key: string): Promise<T | null> {
    const raw = await this.get(key);
    return raw ? JSON.parse(raw) : null;
  }

  async del(key: string): Promise<void> {
    await this.redis.del(key);
  }

  async ttl(key: string): Promise<number> {
    return this.redis.ttl(key);
  }

  async exists(key: string): Promise<boolean> {
    return (await this.redis.exists(key)) === 1;
  }

  async keys(pattern = '*'): Promise<string[]> {
    return this.redis.keys(pattern);
  }
}
